package com.railway.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.railway.service.UserService;
import com.railway.service.impl.UserServiceImpl;

@WebServlet("/UpdatePassword.do")
public class UpdatePasswordServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("application/json");// 后端告知前端 返回的数据 是 json格式(不是html /css)
		String oldPassword = req.getParameter("oldPassword");//原密码
		String newPassword = req.getParameter("newPassword");//新密码
		String newSurePassword = req.getParameter("newSurePassword");//新密码确认
		String username = req.getParameter("username");//用户名
		if(oldPassword == null) {
			oldPassword = "";
		}else {
			oldPassword = req.getParameter("oldPassword");
		}
		
		if(newPassword == null) {
			newPassword = "";
		}else {
			newPassword = req.getParameter("newPassword");
		}
		
		if(newSurePassword == null) {
			newSurePassword = "";
		}else {
			newSurePassword = req.getParameter("newSurePassword");
		}
		UserService us = new UserServiceImpl();
		if(oldPassword.equals("") || newPassword.equals("") || newSurePassword.equals("")) {
			req.setAttribute("failUpdate", "密码或新密码不能为空");
			resp.sendRedirect("refund.jsp");
			return;
		}else {
			if(newPassword.equals(newSurePassword)) {
				int updatePassword = us.updatePassword(newPassword, username, oldPassword);
				ObjectMapper om = new ObjectMapper(); 
				resp.getWriter().print(om.writeValueAsString(updatePassword));
			}
		}
		
	}
	
}
